<template>
  <div>
    <img
      src="https://qiniu.woide.top/avatar/171915066663339.jpeg"
      alt=""
      width="102"
      height="102"
      ref="img"
      v-if="open"
    />
    <div style="float: left">
      <VueDraggable
        ref="el"
        v-model="fileList"
        :animation="150"
        @end="handleDragEnd"
      >
        <div
          v-for="item in fileList"
          :key="item.uid || item.url"
          class="upload-item"
        >
          <ConfigProvider :locale="zhCN">
            <a-image
              :placeholder="true"
              :src="item.url"
               
            />
          </ConfigProvider>
          <DeleteOutlined class="delete-icon" @click="handleRemove(item)" />
          <a-progress
            :percent="item.percent"
            style="position: absolute; left: 0; bottom: 10%; z-index: 9999"
            v-show="item.percent !== 100"
          />
        </div>
      </VueDraggable>
    </div>
    <div style="float: left">
      <a-upload
        list-type="picture-card"
        :before-upload="beforeUpload"
        :show-upload-list="false"
        :capture="null"
        :multiple="true"
        :data="{ id: userInfo.id }"
        name="pu_order_screenshot[]"
        action="https://hzh.woide.top/api/publish/edit_up_img"
        :headers="headers"
        @change="changeUpload"
        :progress="progress"
        :disabled="fileList.length >= props.maxCount"
      >
        <template #default>
          <div>
            <PlusOutlined />
            <div style="margin-top: 8px">点击上传</div>
          </div>
        </template>
      </a-upload>
    </div>
    <ConfigProvider :locale="zhCN">
      <a-tour
        v-model:current="current"
        :open="open"
        :steps="steps"
        @close="tourClose"
        style="width: 100%"
        nextButtonProps="确认"
      />
    </ConfigProvider>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, h } from "vue";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons-vue";
import { message, ConfigProvider } from "ant-design-vue";
import zhCN from "ant-design-vue/es/locale/zh_CN";
import { VueDraggable } from "vue-draggable-plus";
import { deleteImg } from "@/api/public";
import type {
  UploadFile,
  UploadChangeParam,
  UploadProps,
} from "ant-design-vue";

interface Props {
  maxCount: number;
  imgList?: string | string[] | UploadFile[];
}
const userInfo =
  JSON.parse(window.localStorage.getItem("userInfo") || "{}") || {};
const headers = {
  Authorization: userInfo
    ? userInfo.token_type + " " + userInfo.access_token
    : "",
  "X-Requested-With": null,
  referrerPolicy: "no-referrer",
};

const props = defineProps<Props>();
const fileList = ref<any[]>([]);
const emit = defineEmits(["uploadRes"]);
const img = ref(null);

const open = ref<boolean>(
  window.localStorage.getItem("tourState") ? false : true
);
import type { TourProps } from "ant-design-vue";
const current = ref(0);
const progress: UploadProps["progress"] = {
  strokeColor: {
    "0%": "#108ee9",
    "100%": "#87d068",
  },
  strokeWidth: 3,
  format: (percent) => `${parseFloat(percent!.toFixed(2))}%`,
  class: "test",
};
const steps: TourProps["steps"] = [
  {
    title: "上传完图片可进行拖拽排序哦",
    target: () => img.value,
    style: {
      width: "300px",
    },
 
  },
];
// onMounted(() => {
//       if(props.imgList) {
//         initializeFileList();
//       }
// })
const tourClose = () => {
  window.localStorage.setItem("tourState", "true");
  open.value = false;
};

// 将传入的 imgList 转换为 UploadFile 类型的数组
const initializeFileList = () => {
  if (props.imgList) {
    if (Array.isArray(props.imgList)) {
      fileList.value = props.imgList.map((item) => {
        if (typeof item === "string") {
          return {
            uid: item,
            url: item,
            name: item.split("/").pop() || "",
            status: "done",
            percent: 100,
          } as UploadFile;
        }
      });
    }
  }
};

watch(
  () => props.imgList,
  (newVal, oldVal) => {
    initializeFileList();
  },
  { immediate: true }
);

const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  const isPNG = file.type === "image/png";
  const isJPG = file.type === "image/jpg";
  const isJPEG = file.type === "image/jpeg";
  const isGIF = file.type === "image/gif";
  const maxSize = 2 * 1024 * 1024;
  if (!isImage) {
    message.error("只支持上传图片哦");
    return false;
  }
  if (file.size > maxSize) {
    message.error("图片大小不能超过2MB哦");
    return false;
  }
  if (!isPNG && !isJPG && !isJPEG && !isGIF) {
    message.error("只支持上传png、jpg、jpeg,gif格式的图片哦");
    return false;
  }
  if (fileList.value.length >= props.maxCount) {
    message.warning(`你已达到最多上传${props.maxCount}张图片的限制`);
  }
  return true;
};

const key = "上传成功";

const changeUpload = (info: UploadChangeParam<UploadFile>) => {
 

  if (info.file.status === "error") {
    return message.error({ content: "上传失败" });
  }

  const existingFile = fileList.value.find((f) => f.uid === info.file.uid);

  if (info.file.status === "uploading") {
    message.loading({ content: "上传中...", key });

    if (existingFile) {
      existingFile.percent = info.file.percent;
    } else {
      const newFile = { ...info.file, percent: info.file.percent };
      fileList.value.push(newFile);
    }
  }

  if (info.file.status === "done") {
    const res = info.file.response;
    if (res && res.code === 0) {
      message.success({ content: "上传成功", key, duration: 2 });

      if (existingFile) {
        existingFile.url = res.data.img_str;
        existingFile.percent = 100;
      } else {
        const newFile = { ...info.file, url: res.data.img_str, percent: 100 };
        fileList.value.push(newFile);
      }

      emitUrls();
    } else {
      message.error({ content: "图片上传失败" });
    }
  }
};

const handleRemove = async (file: UploadFile) => {
  const index = fileList.value.indexOf(file);
  if (index !== -1) {
    fileList.value.splice(index, 1);
    emitUrls();
    // const res = await deleteImg({ pu_order_screenshot: file.url });
    // if (res.data.code !== 0) {
    //   return message.error({ content: res.data.msg });
    // }
    // if (res.data.code === 0) {
    //   message.success({ content: "删除成功" });
    //   fileList.value.splice(index, 1);
    //   emitUrls();
    // }
  }
};

const handleDragEnd = () => {
  emitUrls();
};

const emitUrls = () => {
  const urls = fileList.value.map((file) => file.url).join(",");
  emit("uploadRes", urls);
};

defineExpose({
  initializeFileList,
});
</script>

<style lang="scss" scoped>
::v-deep .ant-tour {
  background-color: red !important;
}

.upload-item {
  position: relative;
  display: inline-block;
  margin-right: 8px;
  width: 102px;
  height: 102px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  overflow: hidden;
  line-height: 102px;
  box-sizing: border-box;
  transition: all 0.3s ease-in-out;
}

.upload-item img {
  width: 100%;
  transition: opacity 0.3s ease-in-out;
}

.delete-icon {
  position: absolute;
  top: 4px;
  right: 4px;
  cursor: pointer;
  color: red;
  background: white;
  border-radius: 50%;
  padding: 2px;
}
</style>
